using System.Collections.Generic;
using Game.Core;
using PathologicalGames;
using UnityEngine;

namespace Game.Manager
{
	public class GamePoolManager : Singleton<GamePoolManager>
	{
		private Transform poolManager;

		private SpawnPool spawnPool;

		public GamePoolManager()
		{
			poolManager = new GameObject("PoolManager").transform;
			poolManager.parent = Singleton<UIManager>.Instance.canvas;
			spawnPool = poolManager.gameObject.AddComponent<SpawnPool>();
			spawnPool.poolName = "Prefabs";
		}

		public void InitPrefabPool(string path, Transform prefab, int preloadAmount, int limitAmount, int cullAbove, int cullMaxPerPass)
		{
			PrefabPool prefabPool = new PrefabPool(prefab);
			if (!spawnPool._perPrefabPoolOptions.Contains(prefabPool))
			{
				prefabPool.name = path;
				prefabPool.preloadAmount = preloadAmount;
				prefabPool.limitInstances = true;
				prefabPool.limitFIFO = true;
				prefabPool.limitAmount = limitAmount;
				prefabPool.cullDespawned = true;
				prefabPool.cullAbove = cullAbove;
				prefabPool.cullDelay = 10;
				prefabPool.cullMaxPerPass = cullMaxPerPass;
				spawnPool.CreatePrefabPool(prefabPool);
			}
		}

		public Transform Spawn(string path)
		{
			return spawnPool.Spawn(path);
		}

		public void Despawn(Transform obj)
		{
			if (obj != null && spawnPool.IsSpawned(obj))
			{
				spawnPool.Despawn(obj, poolManager, string.Empty);
			}
		}

		public void Despawn(Transform obj, float time)
		{
			spawnPool.Despawn(obj, time, poolManager);
		}

		public void ClearPerfabPool()
		{
			DespawnAllToPool();
			spawnPool.Clear();
		}

		public void DespawnAllToPool()
		{
			List<Transform> list = new List<Transform>(spawnPool._spawned);
			for (int i = 0; i < list.Count; i++)
			{
				if ((bool)list[i])
				{
					Despawn(list[i]);
				}
			}
		}
	}
}
